import React, { useEffect, useRef, useState } from "react";
import {
  Modal,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  useDisclosure,
  Input,
  Select,
  SelectItem,
  Textarea,
} from "@nextui-org/react";
import { showToast } from "../toast";
import { useGlobalState, useHttp } from "@/hooks";

type Props = {
  size?:
    | "xs"
    | "sm"
    | "md"
    | "lg"
    | "xl"
    | "2xl"
    | "3xl"
    | "4xl"
    | "5xl"
    | "full";
  openCallback?: Fn;
  closeCallback?: Fn;
  confirmCallback?: Fn;
  cancelBtnText?: string;
  confirmBtnText?: string;
  triggerBtnText?: string;
  mode: "create" | "edit";
  appId?: number;
  visible?: boolean;
};

const AppModal: React.FC<Props> = ({
  size = "3xl",
  openCallback,
  closeCallback,
  triggerBtnText,
  confirmCallback,
  cancelBtnText,
  confirmBtnText,
  mode,
  appId,
  visible,
}) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [name, setName] = useState("");
  const [introduce, setIntroduce] = useState("");
  const [type, setType] = useState("frontend");

  const isCreateMode = mode === "create";

  useEffect(() => {
    if (visible) {
      handleOpenRef.current();
    }
  }, [visible]);

  const resetInputs = () => {
    setName("");
    setIntroduce("");
    setType("frontend");
  };

  const handleOpen = async () => {
    if (openCallback) {
      openCallback();
    }
    onOpen();
    isCreateMode && resetInputs();
    if (!isCreateMode && appId) {
      const res = await http.get(
        `/api/app/info`,
        { appid: appId },
        { silent: true }
      );
      if (res?.success) {
        setName(res.data.name);
        setIntroduce(res.data.introduce);
        setType(res.data.type);
      }
    }
  };

  const handleOpenRef = useRef(handleOpen);
  handleOpenRef.current = handleOpen;

  const handleClose = () => {
    if (closeCallback) {
      closeCallback();
    }
    onClose();
  };

  useEffect(() => {
    if (appId) {
      // get app info
    }
  }, [appId]);

  const { isLoading, http } = useHttp();
  // const { id } = useGlobalState('user', 'userInfo')

  const handleConfirm = async () => {
    if (!name) {
      showToast("Please enter app name");
      return;
    }

    if (!introduce) {
      showToast("Please enter app description");
      return;
    }

    if (!type) {
      showToast("Please select app type");
      return;
    }

    const res = await http.post(
      isCreateMode ? "/api/app/create" : "/api/app/update",
      {
        ...(!isCreateMode ? { id: appId } : {}),
        name,
        introduce,
        type,
      }
    );

    if (res?.success) {
      handleClose();
    }

    if (confirmCallback) {
      confirmCallback(res?.success);
    }
  };

  return (
    <div className="create-app-modal">
      {isCreateMode && (
        <Button size="md" radius="md" color="primary" onClick={handleOpen}>
          {triggerBtnText || "Add"}
        </Button>
      )}
      <Modal size={size} isOpen={isOpen} onClose={handleClose}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                {isCreateMode ? "Create" : "Edit"} App
              </ModalHeader>
              <ModalBody>
                <div className="flex flex-col gap-4">
                  <div className="control-line">
                    <Input
                      label="Name"
                      size="md"
                      labelPlacement="outside"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="w-full"
                      isRequired
                      placeholder="Enter app name"
                    />
                  </div>
                  <div className="control-line">
                    <Textarea
                      labelPlacement="outside"
                      isRequired
                      label="Description"
                      placeholder="Enter app description"
                      className="w-full"
                      value={introduce}
                      onChange={(e) => setIntroduce(e.target.value)}
                    />
                  </div>
                  <div className="control-line">
                    <Select
                      labelPlacement="outside"
                      isRequired
                      size="md"
                      selectedKeys={[type]}
                      onChange={(e) => setType(e.target.value)}
                      className="w-full"
                      label="Type"
                      placeholder="Select app type"
                    >
                      <SelectItem key="frontend" value={"frontend"}>
                        frontend
                      </SelectItem>
                      <SelectItem key="backend" value={"backend"}>
                        backend
                      </SelectItem>
                    </Select>
                  </div>
                </div>
              </ModalBody>
              <ModalFooter>
                <Button
                  isLoading={isLoading}
                  color="primary"
                  onPress={handleConfirm}
                >
                  {confirmBtnText ?? isCreateMode ? "Create" : "Save"}
                </Button>
                <Button color="primary" variant="flat" onPress={onClose}>
                  {cancelBtnText || "Cancel"}
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
};

export default AppModal;
